﻿namespace Anley.DomainDrivenDesign.Contract.Helper;

/// <summary>
/// Guid生成器
/// </summary>
public class GuidGenerator
    : IGuidGenerator
{
    private static readonly RandomNumberGenerator RandomNumberGenerator = RandomNumberGenerator.Create();

    // 时间戳置首（适用于MySQL）
    public Guid SequentialAsString()
    {
        byte[] randomBytes = new byte[10];
        RandomNumberGenerator.GetBytes(randomBytes);
        long timestamp = DateTime.UtcNow.Ticks / 10000L;
        byte[] timestampBytes = BitConverter.GetBytes(timestamp);
        if (BitConverter.IsLittleEndian)
            Array.Reverse(timestampBytes);
        byte[] guidBytes = new byte[16];
        Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);   // 前6字节为时间戳
        Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);     // 后10字节为随机数
        return new Guid(guidBytes);
    }

    // 时间戳置尾（适用于SQL Server）
    public Guid SequentialAtEnd()
    {
        byte[] randomBytes = new byte[10];
        RandomNumberGenerator.GetBytes(randomBytes);
        long timestamp = DateTime.UtcNow.Ticks / 10000L;
        byte[] timestampBytes = BitConverter.GetBytes(timestamp);
        if (BitConverter.IsLittleEndian)
            Array.Reverse(timestampBytes);
        byte[] guidBytes = new byte[16];
        Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);     // 前10字节为随机数
        Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);  // 后6字节为时间戳
        return new Guid(guidBytes);
    }
}